const Blog = require("./models/Blog");
const Blogtype = require("./models/Blogtype");
const messageDao = require("./messageDao");
const {NotFoundError} = require("../utils/errors");

exports.addBlog = async (info) => {
    const ins = await Blog.create(info);
    return ins.toJSON();
}

exports.getBlogs = async (page, limit, id) => {
    const where = {};
    if (id !== -1) {
        where.categoryId = id;
    }
    const res = await Blog.findAndCountAll({
        include: [{
            model: Blogtype,
            as: "category"
        }],
        where,
        offset: (page - 1) * limit,
        limit
    });
    return {
        total: res.count,
        rows: JSON.parse(JSON.stringify(res.rows))
    }
}

exports.getBlogById = async (id, token) => {
    const ins = await Blog.findByPk(id, {
        include: {
            model: Blogtype,
            as: "category"
        }
    });
    if(!ins){
        throw new NotFoundError();
    }else{
        if(!token){
            ins.scanNumber++;
            await ins.save();
        }
        return ins.toJSON();
    }
}

exports.updateBlog = async (id, info)=>{
    const oldIns = await Blog.findByPk(id);
    if(oldIns.categoryId !== info.categoryId){
        const oldBlogtypeIns = await Blogtype.findByPk(oldIns.categoryId); 
        oldBlogtypeIns.articleCount--;
        await oldBlogtypeIns.save();
        const newBlogtypeIns = await Blogtype.findByPk(info.categoryId);
        newBlogtypeIns.articleCount++;
        await newBlogtypeIns.save();
    }
    await Blog.update(info, {
        where: {
            id
        }
    });
    const ins = await Blog.findByPk(id, {
        include: {
            model: Blogtype,
            as: "category"
        }
    });
    return ins.toJSON();
}

exports.deleteBlog = async (id)=>{
    const blogIns = await Blog.findByPk(id);
    const blogtypeIns = await Blogtype.findByPk(blogIns.categoryId);
    blogtypeIns.articleCount--;
    await blogtypeIns.save();
    await messageDao.deleteMessageByBlogId(id);
    return await blogIns.destroy();
}

exports.getBlogCountByBlogtype = async(blogtypeId)=>{
    return await Blog.count({
        where: {
            categoryId: blogtypeId
        }
    });
}

